package com.ruoyi.learn.java.concurrent;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * 1. CountDownLatch（倒计时门闩）
 * 基本概念
 * 一种同步辅助工具，允许一个或多个线程等待，直到在其他线程中执行的一组操作完成
 *
 * 初始化时指定计数值，通过countDown()方法减少计数，await()方法阻塞直到计数为零
 *
 * 典型应用场景
 * 主线程等待多个子线程完成任务后再继续执行
 *
 * 多个线程等待某个事件发生后同时开始执行
 */
@Slf4j
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 10;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(RandomUtils.nextLong(0, 6000));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + " 执行任务");
                latch.countDown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("所有线程任务执行完毕" + Thread.currentThread().getName());


            }, "Thread-" + i).start();
        }

        latch.await();
        System.out.println("所有线程任务执行完毕");
    }
}